<template>
  <view class="flex-col page">
  <status-bar backgroundColor="rgb(255, 255, 255)"></status-bar>
	<view style="background-color: white; width: 100%;height: 1px;">
	</view>
	<uni-nav-bar color="#000" right-icon="checkmarkempty" @clickRight="next()" left-icon="left" @clickLeft="navBack()" title="添加房间"/>
	<!-- navTo('/pages/roomsguanli/roomsguanli') -->
    <view class="flex-col justify-start flex-auto group_2">
      <view class="flex-row justify-between items-center section">
        <input class="text_2" type="text" v-model="inputValue" placeholder="请输入房间名称"/>
        <view class="text_3" @click="clearInput">×</view>
      </view>
	  <!-- 分割线 -->
	  <hr class="divider">
    </view>
	<view>
		<view class="min-title">推荐房间名称</view>
		<view v-for="(item,index) in roomList">
			<view :class="`recommend-room ${index}`" @click="input(item)">{{item}}</view>
			
		</view>
		
	</view>
  </view>
</template>

<script>
  import {
  		mapState,
  		mapMutations
  	} from 'vuex';
  	import SeniorTable from '@/components/data-table/senior-table.vue'
	//新增房间接口
	import { _addrooms } from '@/service/room.js'
  	//获取实验室信息
  	import {_labomanage} from "@/service/user.js"
  export default {
    components: {
  		SeniorTable
  	},
    data() {
      return {
		  inputValue: '',
		  account_user: '',
		  name_room: '',
		  roomList:['加热房','冷冻房','离心房','基础实验房','应用实验房','教学实验房','综合实验房'],
		  id_lab:'',
		  laboManage:[]
	  };
    },
	onLoad(){
		let newdata;
		try {
			const value = uni.getStorageSync('userInfo');
			if (value != null) {
				console.log(value)
				this.account_user=value.accountNum;
				console.log(value.accountNum)
			}
		} catch (e) {
			console.error(e);
		}
		this.init()
	},
    // onUnload(){
    //   // setTimeout(()=>{
    //     uni.redirectTo({
    //       url:"/pages/roomsguanli/roomsguanli"
    //     });
    //   // },500);
    // },
    methods: {
		async init(){
			let data={
				user:this.account_user
			}
			let res=await _labomanage(data)
			console.log(res.data)
			this.laboManage=res.data
			for(let i=0;i<this.laboManage.length;i++){
				this.id_lab=this.laboManage[i].id
				console.log(this.id_lab)
			}
		},
		clearInput() {
		      this.inputValue = ''
		    },
		input(item) {
			this.inputValue = item;
		},
		//判断是否输入为空
		async validIsEmpty (str, tip) {
			if (str === '') {
				this.$api.msg(`${tip}不能为空`);
				return false;
			}
			return true;
		},
		
		async next(){
			let isValid = await this.validIsEmpty(this.inputValue, "房间名");
			if(isValid){

				let data = {
					account_user:this.account_user,
					name_room:this.inputValue,
					id_lab:this.id_lab
				}
				let res = await _addrooms(data);
				if (res.flag == true){
          uni.navigateBack({});
					setTimeout(()=>{
						uni.hideLoading();		
					}, 500)
				}else{
					setTimeout(()=>{
						uni.hideLoading();
						this.$api.msg(data.message);
					}, 500, () => {
          // 执行回调函数
        });
      }
    }
		},
		navBack(){
			uni.navigateBack({
			})
		},
		// 提交新房间
      async submitNewRoom() {
        console.log('提交新房间:', this.newRoomName);

        if (!this.newRoomName.trim()) {
          console.warn('错误：房间名称为空');
          uni.showToast({
            title: '请输入房间名称',
            icon: 'none'
          });
          return;
        }

        uni.showLoading({
          title: '创建房间中...'
        });

        try {
          console.log('调用新增房间接口，用户:', this.currentUser);
          const result = await _addroom({
            name_room: this.newRoomName,
            owner_account: this.currentUser
          });

          console.log('新增房间接口响应:', result);

          if (result.flag && result.status === 200) {
            console.log('房间创建成功，跳转回设备设置页面');
            uni.showToast({
              title: '房间创建成功',
              icon: 'success'
            });

            // 存储新房间ID
            uni.setStorageSync('newRoomId', result.data.value);

            uni.navigateBack(); // 返回设备设置页面
          } else {
            throw new Error(result.message || '创建房间失败');
          }
        } catch (error) {
          console.error('创建房间失败:', error);
          uni.showToast({
            title: error.message || '创建房间失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      },
	},
  };
</script>

<style scoped lang="scss">
  .page {
    background-color: #ffffff;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
   }
    .group_2 {
      padding: 60rpx 0;
      overflow-y: auto;
	  align-items: center;
	  }
    .section {
	  display: flex;	
	  border-radius: 20rpx;
      width: 85%;
      padding: 29.17rpx 25rpx 29.17rpx 29.17rpx;
      background-color: #d3d3d34d;
	  align-items: center;
	}
	.divider {
		margin-top: 40rpx;
		width: 85%;
		background-color: #f1f1f1;
		opacity: 0.2;
	}
	.min-title {
		font-size: 25rpx;
		margin-left: 7.5%;
		//line-height: 0px;
		color: #8a8a8a;
	}
	.recommend-room {
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		font-size: 35rpx;
		margin-left: 7.5%;
	}
	.text_3 {
		font-size: 40rpx;
		display: contents;
		line-height: 0px;
		color: #8a8a8a;
	}
    .font_2 {
      font-size: 35.42rpx;
      font-family: SourceHanSansCN;
      font-weight: 700;
    }
    .text_5 {
      color: #38383866;
      line-height: 33.33rpx;
	 
    }
    .text_6 {
      color: #38383880;
	  font-family: SourceHanSansCN;
	  font-weight: 700;
	  line-height: 60.92rpx;
    }
      
    
  
</style>